package com.quectel.cms.controller.forum;


import com.quectel.business.contentaudit.ValidatorChain;
import com.quectel.business.contentaudit.ValidatorContext;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.util.SessionHolder;
import com.quectel.cms.vo.forum.ForumSensitiveUploadResp;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.forum.dto.ForumSensitiveDto;
import com.quectel.core.module.forum.service.ForumSensitiveService;
import com.quectel.util.common.*;
import com.quectel.util.kit.StorageKit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 *
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/05/10 11:21
 */
@RestController
@RequestMapping("forumSensitive")
@Tag(name = "ForumSensitiveController", description = "邻友圈敏感词管理相关api")
public class ForumSensitiveController extends BaseController {

    @DubboReference
    private ForumSensitiveService forumSensitiveService;

    @Autowired
    private ValidatorChain validatorChain;

    @GetMapping("downloadFile")
    public Response<Object> downloadFile(String fileId) throws IOException {
        ForumSensitiveDto forumSensitiveDto = forumSensitiveService.selectFileId(fileId);

        try (InputStream inputStream = StorageKit.getObject(fileId)) {
            File tempFile = MyFileUtils.writeFileToTempDir(inputStream, forumSensitiveDto.getFileName(), true);
            String url = uploadFileToPublicBucket(tempFile);
            return Response.ok().wrap(url);
        } catch (IOException e) {
            throw new RuntimeException("文件下载失败", e);
        }
    }

    private String uploadFileToPublicBucket(File file) throws IOException {
        try {
            return StorageKit.uploadToPublicBucketObtainUrl(file);
        } finally {
            file.delete();
        }
    }


    @PostMapping("uploadFileToPrivateBucket")
    @Operation(summary = "文件上传到私有桶")
    public Response<Object> uploadFileToPrivateBucket(MultipartHttpServletRequest request) throws Exception {

        Iterator<String> fileNames = request.getFileNames();
        while (fileNames.hasNext()) {
            String next = fileNames.next();
            List<MultipartFile> files = request.getFiles(next);
            for (MultipartFile file : files) {
                List<Map<Integer, String>> analysis = POIUtils.analysis(file.getInputStream(), 0, 0);
                if (analysis.size()<=0){
                    return Response.error("导入文件不能为空");
                }
                if (analysis.size()>10000){
                    return Response.error("导入文件中不得超过1万条数据");
                }
                ForumSensitiveUploadResp resp = new ForumSensitiveUploadResp();
                resp.setWordNum(analysis.size());
                resp.setFileName(file.getOriginalFilename());

                File tempFile = null;
                try {
                    tempFile = ImageUtils.compressImgWriteToTempDir(file.getInputStream(), file.getOriginalFilename(), false);
                    String url = StorageKit.uploadToPrivateBucketObtainObject(tempFile);
                    resp.setFileId(url);
                    return Response.ok().wrap(resp);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (tempFile != null && tempFile.exists()) {
                        tempFile.delete();
                    }
                }
            }
        }
        return Response.error("上传失败");
    }

    /**
     * 修改单条记录状态
     *
     * @param forumSensitiveDto
     * @return
     */
    @PostMapping("updateStatus")
    @RequirePermissions(values = "notice:edit")
    @Operation(summary = "修改邻友圈敏感词单条记录")
    public Response<Object> updateStatus(@RequestBody ForumSensitiveDto forumSensitiveDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(forumSensitiveDto.getId()));
        if (forumSensitiveService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        //填充基础数据
        fillEditCommonData(forumSensitiveDto);

        forumSensitiveService.updateById(forumSensitiveDto);

        ValidatorContext validatorContext = new ValidatorContext();
        validatorContext.setTenantId(SessionHolder.getSysUser().getTenantId());
        validatorChain.invalidateCache(validatorContext);

        return Response.ok();
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "forumSensitive:list")
    @Operation(summary = "分页获取邻友圈敏感词管理列表")
    public Response<Page<ForumSensitiveDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = forumSensitiveService.queryTotal(request.getParams());

        List<ForumSensitiveDto> list = null;
        if (total > 0) {
            list = forumSensitiveService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<ForumSensitiveDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<ForumSensitiveDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "forumSensitive:edit")
    @Operation(summary = "在编辑时根据id查询邻友圈敏感词管理详情")
    public Response<ForumSensitiveDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (forumSensitiveService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ForumSensitiveDto forumSensitiveDto = forumSensitiveService.selectById(id);

        return Response.<ForumSensitiveDto>ok().wrap(forumSensitiveDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "forumSensitive:info")
    @Operation(summary = "根据id查询邻友圈敏感词管理的详情")
    public Response<ForumSensitiveDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (forumSensitiveService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ForumSensitiveDto forumSensitiveDto = forumSensitiveService.selectById(id);

        return Response.<ForumSensitiveDto>ok().wrap(forumSensitiveDto);
    }

    /**
     * 保存
     *
     * @param forumSensitiveDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "forumSensitive:edit")
    @Operation(summary = "新增邻友圈敏感词管理")
    public Response<Object> save(@RequestBody @Validated ForumSensitiveDto forumSensitiveDto) {

        //填充基础数据
        fillSaveCommonData(forumSensitiveDto);

        forumSensitiveService.save(forumSensitiveDto);

        ValidatorContext validatorContext = new ValidatorContext();
        validatorContext.setTenantId(SessionHolder.getSysUser().getTenantId());
        validatorChain.invalidateCache(validatorContext);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param forumSensitiveDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "forumSensitive:edit")
    @Operation(summary = "根据id修改邻友圈敏感词管理")
    public Response<Object> update(@RequestBody  @Validated ForumSensitiveDto forumSensitiveDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(forumSensitiveDto.getId()));
        if (forumSensitiveService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(forumSensitiveDto);

        forumSensitiveService.updateById(forumSensitiveDto);

        ValidatorContext validatorContext = new ValidatorContext();
        validatorContext.setTenantId(SessionHolder.getSysUser().getTenantId());
        validatorChain.invalidateCache(validatorContext);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "forumSensitive:delete")
    @Operation(summary = "根据多条记录id批量删除邻友圈敏感词管理")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (forumSensitiveService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        forumSensitiveService.deleteBatch(ids);

        ValidatorContext validatorContext = new ValidatorContext();
        validatorContext.setTenantId(SessionHolder.getSysUser().getTenantId());
        validatorChain.invalidateCache(validatorContext);

        return Response.ok();
    }
}
